package org.ants.basecomponent.service.menu.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ants.basecomponent.pojo.menu.Menu;
import org.ants.basecomponent.pojo.menu.MenuInfo;
import org.ants.basecomponent.pojo.menu.MenuNode;
import org.ants.basecomponent.service.menu.MenuTreeService;
import org.ants.basecomponent.util.MenuUtil;

public class MenuTreeServiceImpl implements MenuTreeService{
    private Map<Integer,Menu> loadMenuMap = new HashMap<Integer, Menu>();

    private List<Menu> allMenuList = new ArrayList<Menu>();

    public void load(List<Menu> menuList) {
        for(Menu menu:menuList){
            if(!loadMenuMap.containsKey(menu.getId())){
                allMenuList.add(menu);
                loadMenuMap.put(menu.getId(),menu);
            }
        }
    }

    public MenuInfo getAllMenuInfo(String currentUrl) {
        return getAuthMenuInfoByAuthMenus(allMenuList, currentUrl);
    }

    public MenuInfo getAuthMenuInfoByAuthMenus(List<Menu> authMenuList, String currentUrl) {
        List<Integer> authMenuIdList = new ArrayList<Integer>();
        for(Menu menu : authMenuList){
            authMenuIdList.add(menu.getId());
        }
        return getAuthMenuInfo(authMenuIdList,currentUrl);
    }

    public MenuInfo getAuthMenuInfo(List<Integer> authMenuIdList, String currentUrl) {

    	List<MenuNode> authMenuNodeList = getAuthMenuNodeList(authMenuIdList);
        try {
            MenuInfo menuInfo = getAuthMenuInfo(currentUrl,authMenuNodeList);
            return menuInfo;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    public List<MenuNode> getAuthMenuNodeList(List<Integer> authMenuIdList){
        return getAuthMenuNodeList(allMenuList,authMenuIdList);
    }

    public List<MenuNode> getAuthMenuNodeList(List<Menu> allMenus, List<Integer> authMenuIdList) {
        MenuNode[] treeNodes = new MenuUtil().toTreeByList(authMenuIdList,allMenus);
        List<MenuNode> authMenuNodeList = Arrays.asList(treeNodes);
        return authMenuNodeList;
    }

    public MenuInfo getAuthMenuInfo(String currentUrl,List<MenuNode> authMenuNodeList){
        List<Integer> menuPaths = new ArrayList<Integer>();
        getMyMenusPath(authMenuNodeList, currentUrl, menuPaths);
        MenuInfo menuInfo = new MenuInfo();
        menuInfo.setMenuList(authMenuNodeList);
        menuInfo.setMenuPaths(menuPaths);
        return menuInfo;
    }

    private void getMyMenusPath(List<MenuNode> treeNodes, String currentUrl,
                                List<Integer> pathList) {
        new MenuUtil().getSelectedPath(treeNodes, currentUrl,pathList);
    }
}

